var token='';
try {
    token=  JSON.parse(window.localStorage.getItem("shuangxi")).token;
}catch (e) {
    token='';
}
var page =0;
var book=-1;
$(function () {
    if(window.localStorage.getItem("change")){
        book=window.localStorage.getItem("change")
        window.localStorage.removeItem("change")
    }
    mui.init({
        pullRefresh: {
            container: '#pullrefresh',
            down: {
                callback: function () {
                    previousPage(--page);
                    mui('#pullrefresh').pullRefresh().endPulldownToRefresh();
                }
            },
            up: {
                auto:true,
                contentrefresh: '正在加载...',
                callback: function () {

                    if (page < 1) {
                        fetch("/queryPage.do?token="+token+"&book="+book).then((data)=>data.json()).then((data)=>{
                            if (data) {
                                console.log(data)
                                console.log("token设置完毕")
                                console.log("当前page="+page)
                                page = data.nowBookPage;
                                book=data.nowBook;
                                $("#accountid").val(data.id);
                                window.localStorage.setItem("shuangxi",JSON.stringify(data));
                                nextPage(page);

                            }else {
                                alert("异常啦，可能服务器宕机了")
                            }

                        });
                    }else{
                        nextPage(++page)
                    }

                }
            }
        }
    });
})

function nextPage(index) {
    if (index < 1) {
        index=1;
    }
    let formData = new FormData();
    formData.append("page",index);
    formData.append("token",token);
    //page="+index+"&token="+token
    fetch('/nextPage.do'+"?page="+index+"&token="+token+"&book="+book).then((data)=>data.text()).then((data)=>{
        mui('#pullrefresh').pullRefresh().endPullupToRefresh(false);
        var content = document.body.querySelector('#content');
        var li = document.createElement('p');
        li.innerHTML =data;
        content.appendChild(li)
    });
}
function previousPage(index) {
    if (index < 1) {
        index=1;
        page=1;
    }
    fetch("/nextPage.do?page="+index+"&token="+token+"&book="+book).then((data)=>data.text()).then((data)=>{
        var content = document.body.querySelector('#content');
        var li = document.createElement('p');
        li.innerHTML =data;
        content.insertBefore(li, content.firstChild);
    });
}

